package han.chensing.latos.maker.container;

import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Disposable;
import com.badlogic.gdx.utils.viewport.Viewport;
import han.chensing.latos.maker.windows.dialog.base.BaseDialog;

import java.util.Objects;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;


public class WindowsContainer implements Disposable {
    private final CirnoStage stage;
    private Queue<Runnable> postRuns;

    public WindowsContainer(Viewport viewport){
        this.stage=new CirnoStage();
        this.postRuns=new LinkedBlockingQueue<>();
        stage.setViewport(viewport);
    }

    public void addWindow(Actor window){
        stage.addActor(window);
    }

    public void addWindow(Window window){
        stage.addActor(window);
    }

    @SuppressWarnings("GDXJavaUnsafeIterator")
    public void closeWindows(){
        Array<Actor> actors = stage.getActors();
        Array.ArrayIterator<Actor> iterator = actors.iterator();
        while (iterator.hasNext()){
            Actor actor = iterator.next();
            if (!(actor instanceof BaseDialog dialog))continue;
            if (dialog.getTitleLabel()==null||
                    Objects.equals(dialog.getTitleLabel().getText().toString(),"Tool bar"))continue;
            iterator.remove();
        }
    }

    public void postRun(Runnable runnable){
        postRuns.add(runnable);
    }

    public void act(){
        stage.act();
    }

    public void draw(){
        stage.draw();
        if(!postRuns.isEmpty()) postRuns.poll().run();
    }

    public void onResize(int width,int height){
        stage.getViewport().update(width,height,true);
    }

    public CirnoStage getStage() {
        return stage;
    }

    @Override
    public void dispose() {
        closeWindows();
        stage.dispose();
    }
}
